import { component$ } from '@builder.io/qwik';
import { Link, type RequestHandler, routeLoader$ } from '@builder.io/qwik-city';
import _ from 'lodash';
import { toBigint } from '~/common/bigint';
import List, { ListHeader, ListItem } from '~/components/ui/List';
import { getUserId } from '~/server/authn';
import { noCache } from '~/server/cache-control';
import { db } from '~/server/db';
import logger from '~/server/logger';
import { postCollectionService } from '~/server/service/post-collection-service';
import { postService } from '~/server/service/post-service';

export const onGet: RequestHandler = async (ev) => {
  noCache(ev);
};

export const useLoader = routeLoader$(async (requestEvent) => {
  const userId = getUserId(requestEvent);

  const cidStr = requestEvent.params.id;
  if (_.isEmpty(cidStr)) {
    logger.error(`==> ${requestEvent.pathname}: no id`);
    throw requestEvent.redirect(307, '/me/post-collections');
  }

  const cid = toBigint(cidStr, () => requestEvent.redirect(307, '/me/post-collections'));

  logger.info(`==> ${requestEvent.pathname}: load collection ${cidStr}`);
  const collection = await postCollectionService.findByIdAndUserId(db, cid, userId);
  if (!collection) {
    logger.error(`==> ${requestEvent.pathname}: no collection`);
    throw requestEvent.redirect(307, '/me/post-collections');
  }

  const posts = await postService.findByUserIdAndCollectionId(db, userId, cid);
  logger.info(`==> ${requestEvent.pathname}: load collection ${cidStr} posts: ${posts.length}`);
  return {
    collection,
    posts,
  };
});

export default component$(() => {
  const collectionSignal = useLoader();
  const { collection, posts } = collectionSignal.value;
  return (
    <List>
      <ListHeader class="flex justify-between">
        {collection.title} <Link href={`/create/post?collectionId=${collection.id.toString()}`}>+</Link>
      </ListHeader>
      {posts.map((post) => (
        <ListItem key={post.id.toString()}>
          <Link href={`/posts/${post.id.toString()}`}>{post.title}</Link>
        </ListItem>
      ))}
    </List>
  );
});
